package exam;

public class StockProfit {
    /**
     * 多个
     *
     * @param prices
     * @return
     */

    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) {
            return 0;
        }
        int cur = 0;
        //顶峰
        int vally = 0;
        //谷底
        int peak = 0;
        int income = 0;
        while (cur < prices.length - 1) {
            //找到卖出点,谷底
            while (cur < prices.length - 1 && prices[cur] >= prices[cur + 1]) {
                cur++;
            }
            vally = prices[cur];
            //找到比当前大的值(即最高点,顶峰)
            while (cur < prices.length - 1 && prices[cur] <= prices[cur + 1]) {
                cur++;
            }
            peak = prices[cur];
            income += peak - vally;
            //如果此时cur仍然没有到最后，则进行再一次循环
        }
        return income;

    }

    public static void main(String[] args) {
        StockProfit t = new StockProfit();

        int[] arr = {7, 1, 1, 6, 2, 2};
        System.out.println(t.maxProfit(arr));
        System.out.println(t.maxProfit2(arr));
    }

    /**
     * 1、先判断当前是否已买入
     * 2、定义买价、盈利
     * 3、遍历已知的价格列表
     * 未买入，检查 当前元素 < 下一元素，买入，设置买价
     * 买入，当前元素 > 下一元素 ，盈利 = 当前价 - 买价 ，卖出
     *
     * @param prices
     * @return
     */
    public int maxProfit2(int[] prices) {
        boolean have = false;
        int inprice = 0, profit = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            if (have) {
                if (prices[i] < prices[i + 1]) {
                    continue;
                } else {
                    profit += prices[i] - inprice;
                    have = false;
                }
            } else {
                if (prices[i] < prices[i + 1]) {
                    have = true;
                    inprice = prices[i];
                }
            }
        }
        if (have) {
            profit += prices[prices.length - 1] - inprice;
        }
        return profit;
    }


}